

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Collection;

/**
 * 
 * �����, ����������� ���������� ��� ���������
 * 1) ������� �� ������� 
 * 1.1) ��������� �� �������������
 * 1.2) ��������� �������
 *
 */
public class ChatMessageService {
	private String content;

	public ChatMessageService(Socket socket) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		this.content = reader.readLine();
	}

	public ChatMessageService(Socket socket, String prefix) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		this.content = prefix + reader.readLine();
	}

	public ChatMessageService(BufferedReader reader) throws IOException {
		this.content = reader.readLine();
	}

	public ChatMessageService(String string) throws IOException {
		this.content = string;
	}
	
	public ChatMessageService(ChatThread chatThread) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(chatThread.getSocket().getInputStream()));
		String string = reader.readLine();
		if (string == null) {
			chatThread.getSocket().close();
			this.content = chatThread.getLogin() + " > leaved chat";
		} else {
			this.content = chatThread.getLogin() + " > " + string;
		}
	}
	
	public String getContent() {
		return content;
	}

	public void send(Socket socket) throws IOException {
		PrintWriter writer = new PrintWriter(socket.getOutputStream());
		writer.println(content);
		writer.flush();
	}

	public void sendToGroup(Collection<ChatThread> group) throws IOException {
		for (ChatThread chatThread : group) {
			send(chatThread.getSocket());
		}
	}
	
	public void show() {
		System.out.println(content);
	}
}
